package com.example.walkera.rtsp_android_client.function;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiConfiguration.AuthAlgorithm;
import android.net.wifi.WifiConfiguration.KeyMgmt;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.provider.Settings;
import android.util.Log;

import com.example.walkera.rtsp_android_client.R;
import com.example.walkera.rtsp_android_client.global.GlobalInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class WifiCheck {
	private final static String TAG="WifiCheck";
	public static final int WIFICIPHER_NOPASS = 0x06;
	public static final int WIFICIPHER_WEP = 0x07;
	public static final int WIFICIPHER_WAP = 0x08;
	private static final int RECONNECT_CAMERA = 0x09;
	// 定义WifiManager对象
	private WifiManager mWifiManager;
	// 定义WifiInfo对象
	private WifiInfo mWifiInfo;
	// 扫描出的网络连接列表
	private List<ScanResult> mWifiList;
	// 网络连接列表
	private List<WifiConfiguration> mWifiConfiguration;
	// 定义一个WifiLock
	private WifiLock mWifiLock;
	private GlobalInfo globalInfo = GlobalInfo.getInstance();

	public WifiCheck() {
		// 取得WifiManager对象
		mWifiManager = (WifiManager) (globalInfo.getCurrentApp()).getSystemService(Context.WIFI_SERVICE);
		// 取得WifiInfo对象
		mWifiInfo = mWifiManager.getConnectionInfo();
		//打开wifi
		openWifi();
		// 得到配置好的网络连接
		mWifiConfiguration = mWifiManager.getConfiguredNetworks();
	}

	public static boolean isSSStrong(Context context) {
		int strength = 0;

		WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		WifiInfo info = wifi.getConnectionInfo();
		if (info.getBSSID() != null) {
			strength = WifiManager.calculateSignalLevel(info.getRssi(), 4);
		}
		return strength > 1;
	}

	public static boolean isOnline(Context context) {
		ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

		if (networkInfo != null && networkInfo.isConnected() == true) {
			return true;
		} else {
			return false;
		}
	}

	public static int getWifiStrongLevel( ScanResult scanResult,int level){
		//计算信号强度等级
		WifiManager wifiManager = (WifiManager) GlobalInfo.getInstance().getCurrentApp().getSystemService(Context.WIFI_SERVICE);
		int level_value = wifiManager.calculateSignalLevel(scanResult.level, 5);
		return level_value;
	}

	public void checkWifiPolicy() {
		ContentResolver resolver = GlobalInfo.getInstance().getCurrentApp().getContentResolver();
		int value = Settings.System.getInt(resolver, Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
		if (Settings.System.WIFI_SLEEP_POLICY_NEVER != value) {
			AlertDialog.Builder builder = new AlertDialog.Builder(GlobalInfo.getInstance().getCurrentApp());
			builder.setMessage(GlobalInfo.getInstance().getCurrentApp().getString(R.string.check_wifi_policy));
			builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
			AlertDialog checkDialog = builder.create();
			checkDialog.setCancelable(true);
			checkDialog.show();
		}
	}

	// 打开WIFI
	public void openWifi() {
		if (!mWifiManager.isWifiEnabled()) {
			mWifiManager.setWifiEnabled(true);
		}
	}

	// 关闭WIFI
	public void closeWifi() {
		if (mWifiManager.isWifiEnabled()) {
			mWifiManager.setWifiEnabled(false);
		}
	}

	// 检查当前WIFI状态
	public int checkState() {
		return mWifiManager.getWifiState();
	}

	// 锁定WifiLock
	public void acquireWifiLock() {
		mWifiLock.acquire();
	}

	// 解锁WifiLock
	public void releaseWifiLock() {
		// 判断时候锁定
		if (mWifiLock.isHeld()) {
			mWifiLock.acquire();
		}
	}

	// 创建一个WifiLock
	public void creatWifiLock() {
		mWifiLock = mWifiManager.createWifiLock("Test");
	}

	// 得到配置好的网络
	public List<WifiConfiguration> getConfiguration() {
		// 得到配置好的网络连接
//		mWifiConfiguration = mWifiManager.getConfiguredNetworks();
		return mWifiConfiguration;
	}

	// 指定配置好的网络进行连接
	public void connectConfiguration(int index) {
		// 索引大于配置好的网络索引返回
		if (index > mWifiConfiguration.size()) {
			return;
		}
		// 连接配置好的指定ID的网络
		mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId, true);
	}

	public void startScan() {
		//扫描
		mWifiManager.startScan();
		// 得到扫描结果
//		mWifiList = mWifiManager.getScanResults();
		// 得到配置好的网络连接
		mWifiConfiguration = mWifiManager.getConfiguredNetworks();
	}

	// 查看扫描结果
	public StringBuilder lookUpScan() {
		StringBuilder stringBuilder = new StringBuilder();
		for (int i = 0; i < mWifiList.size(); i++) {
			stringBuilder.append("Index_" + new Integer(i + 1).toString() + ":");
			// 将ScanResult信息转换成一个字符串包
			// 其中把包括：BSSID、SSID、capabilities、frequency、level
			stringBuilder.append((mWifiList.get(i)).toString());
			stringBuilder.append("/n");
		}
		return stringBuilder;
	}

	// 得到接入点MAC地址
	public String getMacAddress() {
		return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress();
	}

	// 得到接入点的BSSID
	public String getBSSID() {
		return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID();
	}

	// 得到接入点IP地址
	public int getIPAddress() {
		return (mWifiInfo == null) ? 0 : mWifiInfo.getIpAddress();
	}

	// 得到接入点连接的ID
	public int getNetworkId() {
		return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId();
	}

	// 得到接入点WifiInfo的所有信息包
	public String getWifiInfo() {
		return (mWifiInfo == null) ? "NULL" : mWifiInfo.toString();
	}

	//得到接入点wifi的ssid
	public String getSSID(){
//		getSSID()获取到的SSID名称和手机的Android版本有关，如果是Android 4.2（API Level = 17）及其以上的版本，获取到的SSID名称是有双引号的，即"haha"，如果是Android 4.2以下的版本，获取到的SSID名称没有双引号，即haha
		return (mWifiInfo == null) ? "NULL" : mWifiInfo.getSSID();
	}

	public String getSSIDWithoutQuotationMark(){
		//		getSSID()获取到的SSID名称和手机的Android版本有关，如果是Android 4.2（API Level = 17）及其以上的版本，获取到的SSID名称是有双引号的，即"haha"，如果是Android 4.2以下的版本，获取到的SSID名称没有双引号，即haha
		String strTempSSID="NULL";
		if (mWifiInfo!=null){
			String strWifiSSID=mWifiInfo.getSSID();
			if (strWifiSSID.startsWith("\"")&&strWifiSSID.endsWith("\"")){
				strTempSSID=strWifiSSID.substring(strWifiSSID.indexOf("\"")+1,strWifiSSID.lastIndexOf("\""));
			}
		}
		return strTempSSID;
	}

	// 添加一个网络并连接,返回一个添加的networkId
	public int addNetwork(WifiConfiguration wifiConfig) {
		int connectNetID=-1;
		// 得到配置好的网络连接
		List<WifiConfiguration> tmpAlreadyWifiConfigList = mWifiManager.getConfiguredNetworks();
		if (tmpAlreadyWifiConfigList!=null){//说明之前有链接好的网络，这个时候，我们需要移除和端开，以保证一直只有一个有效链接
			for (int i=0;i<tmpAlreadyWifiConfigList.size();i++){//依次端口之前已经链接好的网络
				WifiConfiguration tmpWifiConfig=tmpAlreadyWifiConfigList.get(i);
				if (tmpWifiConfig.SSID.compareTo(wifiConfig.SSID)==0) {//如果需要连接的wifi已经连接了
					connectNetID = tmpWifiConfig.networkId;
					continue;
				}
				disconnectWifi(tmpAlreadyWifiConfigList.get(i).networkId);
			}
		}
		if (connectNetID!=-1) return connectNetID;

		connectNetID = mWifiManager.addNetwork(wifiConfig);
		if (connectNetID!=-1) {//如果返回-1,表示添加失败
			boolean bRet = mWifiManager.enableNetwork(connectNetID, true);
			Log.d(TAG, "addNetwork: "+connectNetID+" enable return:"+bRet);
		}
		return connectNetID;
	}

	// 断开指定ID的网络
	public void disconnectWifi(int netId) {
		if (netId!=-1) {
			mWifiManager.disableNetwork(netId);
			mWifiManager.disconnect();
			mWifiManager.removeNetwork(netId);
		}
	}

	// wifi connection is ok
	public boolean isWifiConnect(Context context) {
		Log.d(TAG, "isWifiConnect: [Normal] -- WifiCheck: isWifiConnect?");
		if (context != null) {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mWiFiNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
			if (mWiFiNetworkInfo != null) {
				WifiManager mWifi = (WifiManager) GlobalInfo.getInstance().getCurrentApp().getSystemService(Context.WIFI_SERVICE);
				WifiInfo wifiInfo = mWifi.getConnectionInfo();
				if (wifiInfo.getIpAddress() != 0) {
					Log.d(TAG, "isWifiConnect: [Normal] -- AppStart: isWifiConnect? true!");
					return mWiFiNetworkInfo.isAvailable();
				}

			}
		}
		Log.d(TAG, "isWifiConnect: [Normal] -- AppStart: isWifiConnect? false");
		return false;
	}

	public boolean isWifiConnected(Context context, String nameFilter) {
		if (context != null) {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
//			NetworkInfo tmpWiFiNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
			NetworkInfo tmpWiFiNetworkInfo=mConnectivityManager.getActiveNetworkInfo();
			if (tmpWiFiNetworkInfo != null) {
				WifiManager mWifi = (WifiManager) GlobalInfo.getInstance().getCurrentApp().getSystemService(Context.WIFI_SERVICE);
				WifiInfo wifiInfo = mWifi.getConnectionInfo();
				if (wifiInfo.getIpAddress() != 0 && wifiInfo.getSSID().contains(nameFilter) == true) {
					return true;
				}

			}
		}

		return false;
	}

	public static boolean isWifiContected(Context context) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
//		NetworkInfo wifiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		NetworkInfo wifiNetworkInfo =connectivityManager.getActiveNetworkInfo();
		if (wifiNetworkInfo!=null&&wifiNetworkInfo.isConnected()) {

			Log.i(Thread.currentThread().getName(), "isWifiContected");
			return true;
		}
		Log.i(Thread.currentThread().getName(), "isWifiDisconnected");
		return false;

	}

	public int getSecurity(ScanResult result) {
		if (result.capabilities.contains("WEP")) {
			return WIFICIPHER_WEP;
		} else if (result.capabilities.contains("WPA")) {
			return WIFICIPHER_WAP;
		} else {
			return WIFICIPHER_NOPASS;
		}
		// return 1;
	}

	public WifiConfiguration CreateWifiInfo(String SSID, String Password, int Type) {
		WifiConfiguration config = new WifiConfiguration();
		config.allowedAuthAlgorithms.clear();
		config.allowedGroupCiphers.clear();
		config.allowedKeyManagement.clear();
		config.allowedPairwiseCiphers.clear();
		config.allowedProtocols.clear();
		config.SSID = "\"" + SSID + "\"";
		if (Type == WIFICIPHER_NOPASS) // Data.WIFICIPHER_NOPASS
		{
			config.hiddenSSID = true;
//			config.wepKeys[0] = "";
			config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
//			config.wepTxKeyIndex = 0;
		}
		if (Type == WIFICIPHER_WEP) // Data.WIFICIPHER_WEP
		{
			if (Password.length() != 0) {
				int length = Password.length();
				// WEP-40, WEP-104, and 256-bit WEP
				// (WEP-232?)
				if ((length == 10 || length == 26 || length == 58) && Password.matches("[0-9A-Fa-f]*")) {
					config.wepKeys[0] = Password;
				} else {
					config.wepKeys[0] = '"' + Password + '"';
				}
			}
			config.allowedKeyManagement.set(KeyMgmt.NONE);
			config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
			config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED);
			config.wepTxKeyIndex = 0;
		}
		if (Type == WIFICIPHER_WAP) // Data.WIFICIPHER_WPA
		{
			config.preSharedKey = "\"" + Password + "\"";
			config.hiddenSSID = true;
			config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
			config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
			config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
			config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
			config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
			config.status = WifiConfiguration.Status.ENABLED;
		}
		return config;
	}

	public int connectWifi(String SSID, String Password, int Type) {
		WifiConfiguration config = CreateWifiInfo(SSID, Password, Type);
		return addNetwork(config);
	}

	// 分为三种情况：1没有密码2用wep加密3用wpa加密

	public List<ScanResult> getWifiListByFilter(String nameFilter) {
//		WifiManager wifiManager = (WifiManager) globalInfo.getAppContext().getSystemService(Context.WIFI_SERVICE);
//		List<ScanResult> wifiList = wifiManager.getScanResults();

		List<ScanResult> wifiList=getWifiList();
		List<ScanResult> tempList = new LinkedList<ScanResult>();
		for (int ii = 0; ii < wifiList.size(); ii++) {
			if ((wifiList.get(ii).SSID).contains(nameFilter) == false) {
				tempList.add(wifiList.get(ii));
			}
		}
		wifiList.removeAll(tempList);
		return wifiList;
	}

	public List<ScanResult> getWifiList() {
//		WifiManager wifiManager = (WifiManager) (GlobalInfo.getInstance().getCurrentApp().getSystemService(Context.WIFI_SERVICE));
//		List<ScanResult> wifiList = wifiManager.getScanResults();
		//		wifiManager.startScan();
		mWifiList=mWifiManager.getScanResults();
//		startScan();
		return mWifiList;
	}

	public ScanResult hasThisWifi(String ssid) {
		List<ScanResult> retList = getWifiList();
		for (ScanResult temp : retList) {
			if (temp.SSID.equals(ssid) == true) {
				return temp;
			}
		}
		return null;
	}

	//JIRA ICOM-1991 ICOM-1992 Begin Add by b.jiang 2015-09-21
	public List<ScanResult> wifiListSortWithStartString(List<ScanResult> wifiList, String startString) {
		List<ScanResult> tempWifiList1 = new ArrayList<ScanResult>();
		List<ScanResult> tempWifiList2 = new ArrayList<ScanResult>();
		int i;
		String tempSsid;
		for (i = 0; i < wifiList.size(); i++) {
			Log.d(TAG, "wifiListSortWithStartString: wifi Signal level ssid " + wifiList.get(i).SSID + "=" + wifiList.get(i).level);
		}
		// 筛选出以字符串startString开头的ssid;
		for (i = 0; i < wifiList.size(); i++) {
			tempSsid = wifiList.get(i).SSID;
			if (tempSsid.startsWith(startString)) {
				tempWifiList1.add(wifiList.get(i));
			} else {
				tempWifiList2.add(wifiList.get(i));
			}
		}
		// 将ssid按信号强弱排序，信号强的排在前面;
		if (tempWifiList1.size() > 0) {
			wifiListSortWithSignalLevel(tempWifiList1);
		}
		if (tempWifiList2.size() > 0) {
			wifiListSortWithSignalLevel(tempWifiList2);
		}

		for (i = 0; i < tempWifiList2.size(); i++) {
			tempWifiList1.add(tempWifiList2.get(i));
		}

		for (i = 0; i < tempWifiList1.size(); i++) {
			Log.d(TAG, "wifiListSortWithStartString: sort ago wifi Signal level ssid " + tempWifiList1.get(i).SSID + "="
					+ tempWifiList1.get(i).level);
		}

		return tempWifiList1;
	}

	public List<ScanResult> wifiListSortWithSignalLevel(List<ScanResult> wifiList) {
		for (int i = 0; i < wifiList.size() - 1; i++) {
			for (int j = 0; j < wifiList.size() - i - 1; j++) {
				if (wifiList.get(j).level < wifiList.get(j + 1).level) {
					ScanResult temp = wifiList.get(j);
					wifiList.set(j, wifiList.get(j + 1));
					wifiList.set(j + 1, temp);
				}
			}
		}
		return wifiList;
	}
	//JIRA ICOM-1991 ICOM-1992 End Add by b.jiang 2015-09-21

	//用hashMap来存储结果，过滤掉相同的ssid
	public HashMap<String,ScanResult> mhashMapScanResult=new HashMap<>();
	public List<ScanResult> getWifiListWithFilter(){
		mhashMapScanResult.clear();

		List<ScanResult> tmpWifiList=getWifiList();
		for (int i=0;i<tmpWifiList.size();i++){//这里利用map来过滤掉相同的ssid
			mhashMapScanResult.put(tmpWifiList.get(i).SSID,tmpWifiList.get(i));
		}


		List<ScanResult> tmplistScanResult = new ArrayList<>();

		//遍历hashmap
//		for (HashMap.Entry<String,ScanResult>entry:mhashMapScanResult.entrySet()){
//			tmplistScanResult.add(entry.getValue());
//		}

		ScanResult tempScanResult=null;
		//第二种遍历hashmap的方式:通过迭代器
		Iterator<HashMap.Entry<String,ScanResult>> iter = mhashMapScanResult.entrySet().iterator();
		while (iter.hasNext()){
			HashMap.Entry<String,ScanResult> entry = iter.next();
			//这里添加一个过滤操作,链接的wifi不进行排序
			if (getSSIDWithoutQuotationMark().compareTo(entry.getKey())==0){
				tempScanResult=entry.getValue();
				continue;
			}
			tmplistScanResult.add(entry.getValue());
		}

		List<ScanResult> retListScanResult=wifiListSortWithSignalLevel(tmplistScanResult);
		if (tempScanResult!=null){//将连接的wifi添加到最前面
			retListScanResult.add(0,tempScanResult);
		}
		return retListScanResult;
	}

}
